package cn.hh.hrm.userdetail;


import cn.hh.hrm.domain.LoginUser;
import cn.hh.hrm.domain.Permission;
import cn.hh.hrm.mapper.LoginUserMapper;
import cn.hh.hrm.util.ValidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetails implements UserDetailsService {
    @Autowired
    private LoginUserMapper loginUserMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据用户名查询用户
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser = loginUserMapper.selectOne(loginUser);
        //判断是否有该用户
        ValidUtils.assertNotNull(loginUser, "对不起，没有该用户！");
        //查询用户的权限
        ArrayList<SimpleGrantedAuthority> authors = new ArrayList<>();
        List<Permission> list =  loginUserMapper.getPermissions(loginUser.getId());
        list.stream().forEach(permission -> {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getSn());
            authors.add(simpleGrantedAuthority);
        });
        return new User(loginUser.getUsername(),loginUser.getPassword(),authors);
    }
}
